/*
 * 文件名：SetupFinController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年1月11日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.cap.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.domain.LookInfoDomain;
import top.infopub.mgr.cap.domain.SetupFinDomain;
import top.infopub.mgr.cap.dto.SetupFinDto;
import top.infopub.mgr.cap.jsonvo.LookInfoJsonVo;
import top.infopub.mgr.cap.jsonvo.SetupFinJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.LookInfoBankService;
import top.infopub.mgr.cap.service.LookInfoBeginService;
import top.infopub.mgr.cap.service.SetupFinService;
import top.infopub.mgr.cap.vo.LookInfoBeginVo;
import top.infopub.mgr.cap.vo.SetupFinVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.domain.CollectDomain;
import top.infopub.mgr.mkt.service.PreProjectService;
import top.infopub.mgr.mkt.service.ProjectInfoService;
import top.infopub.mgr.sg.dao.CitySurveyDao;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.sg.vo.CitySurveyVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.cap.LookInfoBank;
import top.infopub.model.cap.SetupFin;
import top.infopub.model.cap.SetupFinAtt;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.PreProject;
import top.infopub.model.mkt.ProjectInfo;
import top.infopub.model.sg.CitySurvey;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 融资立项管理
 * @author wuzhiyang
 * @version 2020年1月10日
 * @see SetupFinController
 * @since
 */
@Controller
@RequestMapping("/setupFin")
public class SetupFinController extends GenericFlowController {

    @Autowired
    private SetupFinService setupFinService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private PreProjectService preProjectService;

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private CitySurveyDao citySurveyDao;

    @Autowired
    private LookInfoBeginService lookInfoBeginService;
    @Autowired
    private LookInfoBankService lookInfoBankService;

    @Autowired
    private ProjectInfoService projectInfoService;
    @Autowired
    private CapProcessManageService capProcessManageService;

    /**
     * 融资立项列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "cap/lay-setupFin-list";
    }

    /**
     * 融资立项列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<LookInfoDomain> queryDataByCondition(LookInfoBeginVo lookInfoBeginVo, ParamPage paramPage) {
        Page<LookInfoDomain> page = new Page<LookInfoDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = setupFinService.selectByDomainWhere(page, lookInfoBeginVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资立项列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<SetupFinDomain> queryMyCheckDataByCondition(SetupFinVo setupFinVo,
                                                             ParamPage paramPage) {
        Page<SetupFinDomain> page = new Page<SetupFinDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (setupFinVo.getEndDate() != null) {
            setupFinVo.setEndDate(DateUtils.addDays(setupFinVo.getEndDate(), 1));
        }
        //增加addby
        setupFinVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = setupFinService.selectMyCheckByDomainWhere(page, setupFinVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资立项-新增
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //返回所有预立项中的项目名称
        List<PreProject> selectPreProject = preProjectService.selectPreProject(null);
        request.setAttribute("allProName", selectPreProject);
        //返回所有承贷企业的单位名称
        List<CoopInfo> coopCode = coopInfoService.selectByCoopCode(null);
        request.setAttribute("coopInfoName", coopCode);
        return "cap/lay-setupFin-add";
    }

    /**
     * 通过项目id查询预立项信息记录
     */
    @RequestMapping("/getSetupFinByProId")
    @ResponseBody
    public Map<String, Object> getSetupFinByProId(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String proCode = request.getParameter("proCode");
            List<PreProject> preProject = preProjectService.selectPreProject(proCode);
            if (preProject.size() == 1) {
                map.put("proList", preProject.get(0));
            }
        }
        catch (Exception e) {
            log.error("根据项目ID获取预定项目信息异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 融资尽调-新增
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
//    public RspVo save(SetupFinAssist setupFinAssist) {
//
//        //主表-融资立项
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        try {
//            Date date = simpleDateFormat.parse(setupFinAssist.getEstablishmentTime());
//            setupFinAssist.setSetupDate(date);
//        }
//        catch (ParseException e) {
//            e.printStackTrace();
//        }
//        setupFinAssist.setHrDeptId(setupFinAssist.getHrDeptid());
//        setupFinAssist.setHrOrgId(setupFinAssist.getHrOrgid());
//        setupFinAssist.setStaffName(setupFinAssist.getStaffname());
//        setupFinAssist.setHrStaffApplyId(setupFinAssist.getHrStaffApplyid());
//        PreProjectDomain byProCode = preProjectService.queryByProCode(setupFinAssist.getProname());
//        setupFinAssist.setProCode(setupFinAssist.getProname());
//        //添加项目名称
////        setupFinAssist.setProName(byProCode.getProName());
//        //添加城市调研信息ID
////        setupFinAssist.setSgCityId(byProCode.getSgCityId());
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//        String id = IdFactory.getUUIDUpper();
//        setupFinAssist.setId(id);
//        setupFinAssist.setAddBy(vo.getId());
//        setupFinAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String codes = codeGeneratorConfigService.generatorCode("cap_setup_fin");
//        setupFinAssist.setCodes(codes);
//        // 处理processId
//        setupFinAssist.setProcessId(IdFactory.getUUIDUpper());
//        setupFinAssist.setProcessStatus("1");//审批中
//        setupFinAssist.setTypes("1");//PPP项目
//        setupFinAssist.setUptBy(vo.getId());
//        setupFinAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //融资费用-费用明细处理
//        List<SetupFinCost> setupFinCosts = new ArrayList<SetupFinCost>();
//        String[] showIdxs1 = setupFinAssist.getSubFinCostShowIdx();
//        if (showIdxs1 != null && showIdxs1.length > 0) {
//            for (int i = 0; i < showIdxs1.length; i++ ) {
//                String showIdx1 = showIdxs1[i];
//                String costMemo = setupFinAssist.getSubCostMemo()[i];
//                String costAmount = setupFinAssist.getSubCostAmount()[i];
//                if (StringUtils.isEmpty(showIdx1) && StringUtils.isEmpty(showIdx1)) {
//                    continue;
//                }
//                String costid = IdFactory.getUUIDUpper();//自动生成主键
//                SetupFinCost setupFinCost = new SetupFinCost();
//                setupFinCost.setId(costid);
//                setupFinCost.setSetupFinId(id);
//                setupFinCost.setShowIdx(Integer.parseInt(showIdx1));
//                setupFinCost.setCostMemo(costMemo);
//                setupFinCost.setCostAmount(new BigDecimal(costAmount));
//                setupFinCost.setAddBy(vo.getId());
//                setupFinCost.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                setupFinCosts.add(setupFinCost);
//            }
//        }
//
//        //工作节点
//        List<SetupFinNode> setupFinNodes = new ArrayList<SetupFinNode>();
//        String[] showIdxs2 = setupFinAssist.getSubWorkNodeShowIdx();
//        if (showIdxs2 != null && showIdxs2.length > 0) {
//            for (int i = 0; i < showIdxs2.length; i++ ) {
//                String showIdx2 = showIdxs2[i];
//                String keyPonit = setupFinAssist.getSubKeyPoint()[i];
//                String progMemo = setupFinAssist.getSubProMemo()[i];
//                if (StringUtils.isEmpty(showIdx2) && StringUtils.isEmpty(showIdx2)) {
//                    continue;
//                }
//                String nodeid = IdFactory.getUUIDUpper();//自动生成主键
//                SetupFinNode setupFinNode = new SetupFinNode();
//                setupFinNode.setId(nodeid);
//                setupFinNode.setSetupFinId(id);
//                setupFinNode.setShowIdx(Integer.parseInt(showIdx2));
//                setupFinNode.setKeyPonit(keyPonit);
//                setupFinNode.setProgMemo(progMemo);
//                setupFinNode.setAddBy(vo.getId());
//                setupFinNode.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                setupFinNodes.add(setupFinNode);
//            }
//        }
//
//        //工作目标
//        List<SetupFinAim> setupFinAims = new ArrayList<SetupFinAim>();
//        String[] showIdxs3 = setupFinAssist.getSubWorkTargetShowIdx();
//        if (showIdxs3 != null && showIdxs3.length > 0) {
//            for (int i = 0; i < showIdxs3.length; i++ ) {
//                String showIdx3 = showIdxs3[i];
//                String workAim = setupFinAssist.getSubWorkAim()[i];
//                String timeNode = setupFinAssist.getSubTimeNode()[i];
//                String taskMemo = setupFinAssist.getSubTaskMemo()[i];
//                if (StringUtils.isEmpty(showIdx3) && StringUtils.isEmpty(showIdx3)) {
//                    continue;
//                }
//                String aimid = IdFactory.getUUIDUpper();//自动生成主键
//                SetupFinAim setupFinAim = new SetupFinAim();
//                setupFinAim.setId(aimid);
//                setupFinAim.setSetupFinId(id);
//                setupFinAim.setShowIdx(Integer.parseInt(showIdx3));
//                setupFinAim.setWorkAim(workAim);
//                setupFinAim.setTimeNode(timeNode);
//                setupFinAim.setTaskMemo(taskMemo);
//                setupFinAim.setAddBy(vo.getId());
//                setupFinAim.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                setupFinAims.add(setupFinAim);
//            }
//        }
//
//        //上传附件
//        List<SetupFinAtt> setupFinAtts = new ArrayList<SetupFinAtt>();
//        String[] fileAtts = setupFinAssist.getFileAtt();
//        if (fileAtts != null) {
//            for (String file : fileAtts) {
//                SetupFinAtt setupFinAtt = createFileAtt(vo, id, file);
//                setupFinAtts.add(setupFinAtt);
//            }
//        }
//        setupFinService.saveSetupFin(setupFinAssist, setupFinAims, setupFinAtts, setupFinCosts,
//            setupFinNodes);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
//            "融资管理 -新增融资立项：项目名=" + setupFinAssist.getProName(), null);
//        return RspVo.getSuccessResponse();
//    }

    private SetupFinAtt createFileAtt(AuthorizationVO vo, String setupFinId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        SetupFinAtt fileAtt = new SetupFinAtt();
        fileAtt.setId(IdFactory.getUUIDUpper());
        fileAtt.setSetupFinId(setupFinId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "setupFinAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传融资立项附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询融资立项详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 融资立项Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id,String proCode) {
        request.setAttribute("proCode",proCode);
        request.setAttribute("id",id);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        SetupFin setupFin = setupFinService.selectById(id);
        request.setAttribute("isAuditFlag", "1");
        if (setupFin!=null){
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), setupFin.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), setupFin.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(setupFin.getProcessId()) && setupFin.getProcessId().length() > 10){
                request.setAttribute("processId", setupFin.getProcessId());
                String auditTabFlag = capProcessManageService.checkShowAuditTab(setupFin.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), setupFin.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        return new ModelAndView("cap/lay-ProjectApplication-detail");
    }

    /**
     * 根据id查询合作单位信息
     * @param
     * @return
     * @see
     */
    @RequestMapping("/getCoopAllByCoopCode")
    @ResponseBody
    public Map<String, Object> getCoopAllByCoopCode(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String coopCode = request.getParameter("coopCode");
            List<CoopInfo> coopInfoList = coopInfoService.selectByCoopCode(coopCode);
            map.put("coopInfoList", coopInfoList);
        }
        catch (Exception e) {
            log.error("根据单位ID获取合作单位信息异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 融资立项详情
     */
    @RequestMapping("/querySetupFin")
    @ResponseBody
    public RspVo querySetupFin(String id) {
        return  setupFinService.queryDetailById(id);
    }

    @RequestMapping("/saveOrEdit")
    @ResponseBody
    public RspVo saveOrEdit(String bodyStr,Integer submitType){
        AuthorizationVO userDtl = SessionUserUtils.getSessionAttributeForUserDtl();
        String s = StringEscapeUtils.unescapeJava(bodyStr);
        SetupFinJsonVo vo = JSON.parseObject(s, SetupFinJsonVo.class);
        SetupFinDto setupFin = vo.getSetupFin();
        SetupFin setupFin1 = new SetupFin();
        BeanUtils.copyProperties(setupFin,setupFin1);
        if (StringUtils.isBlank(setupFin.getId())){ //新增
            ProjectInfo projectInfo1 = projectInfoService.selectByProName(setupFin.getProName());
            if (projectInfo1!=null){
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("项目名称【" + setupFin.getProName()
                        + "】已经存在~");
            }
            SetupFin setupFin2 = setupFinService.selectByProName(setupFin.getProName());
            if (setupFin2!=null){
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("项目名称【" + setupFin2.getProName()
                        + "】已经存在~");
            }

            //根据地址去查询城市调研信息
            CitySurveyVo citySurveyVo = new CitySurveyVo();
            citySurveyVo.setRefProvinceId(setupFin.getRefProvinceId());
            citySurveyVo.setRefCityId(setupFin.getRefCityId());
            citySurveyVo.setRefAreaId(setupFin.getRefAreaId());
            CitySurvey citySurvey = citySurveyDao.selectByAddress(citySurveyVo);
            setupFin1.setSgCityId(citySurvey.getId());
            setupFin1.setCodes(IdFactory.getUUIDUpper());
            setupFin1.setAddBy(userDtl.getId());
            setupFin1.setProCode(setupFin.getProCode());
            setupFin1.setAddTime(new Date());
            setupFin1.setUptBy(userDtl.getId());
            setupFin1.setUptTime(new Date());
        }
        return setupFinService.saveAll(userDtl,setupFin1,vo.getSetupFinancials(),submitType,bodyStr);
    }

    /**
     * 融资立项列表所需数据
     * @return
     */
    @RequestMapping("/queryDrop")
    @ResponseBody
    public RspVo queryDrop(String proCode){
        LookInfoJsonVo lookInfoJsonVo = new LookInfoJsonVo();
        //根据proCode 去查询尽调金融机构
        List<LookInfoBank> banks = lookInfoBankService.selectByProCode(proCode);
        lookInfoJsonVo.setLookInfoBank(banks);
        return RspVo.getSuccessResponse(lookInfoJsonVo);
    }


    /**
     * 获取项目信息收集页面所需数据
     * **/
    @RequestMapping("/getSetupNew")
    @ResponseBody
    public RspVo getCollectDomain(){
        //生成项目编码
        CollectDomain collectDomain = new CollectDomain();
        String procode = codeGeneratorConfigService.generatorCode("CAP_SETUP_PROCODE");
        collectDomain.setProCode(procode);
        return RspVo.getSuccessResponse(collectDomain);
    }
    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg,String isTrack) {

        //融资立项
        capProcessManageService.auditProject(id, processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }
}
